package org.fuxia.im.core.utils;

/**
 * IP地址转换工具
 * 
 * @author Fuxia
 * @create @date Jan 14, 2012-12:30:39 AM
 * @comment
 */
public class IpUtils
{
	private static final byte[]	ipByte	= new byte[32];
	private static int			count	= 0;

	/**
	 * 将Ip地址转换成32位字节数组
	 * 
	 * @param ipAddress
	 * @return
	 */
	public static byte[] ipToByte(String ipAddress)
	{
		byte[] current = ipByte.clone();
		String[] segments = ipAddress.split("\\.");
		if (segments.length != 4)
			throw new RuntimeException("Error ip address");
		int segmentsLen = segments.length;
		for (int i = 0; i < segmentsLen; i++)
		{
			String temp = segments[i];
			int intNum = 0;
			try
			{
				intNum = Integer.parseInt(temp);
				byte[] curByte = ByteUtils.intToByte(intNum, 8);
				count = ByteUtils.copyToDestByte(curByte, current, count);
			}
			catch (NumberFormatException e)
			{
				throw new RuntimeException("Error ip address");
			}
			catch (RuntimeException e)
			{
				e.printStackTrace();
				throw new RuntimeException("Error ip address");
			}

		}
		count = 0;
		return current;
	}

	/**
	 * 将32位表示的ip地址转换成十进制点分法的ip地址
	 * 
	 * @param byteIp
	 * @return
	 */
	public static String byteToString(byte[] byteIp)
	{
		ECIterator<byte[]> iterator = ByteIterator.getIterator(byteIp);
		StringBuilder ip = new StringBuilder();
		while (iterator.hasNext())
		{
			byte[] segment = iterator.nextN(8);
			int num = ByteUtils.byteToInt(segment);
			ip.append(num);
			if (iterator.hasNext())
			{
				ip.append(".");
			}
		}
		return ip.toString();
	}

}
